package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtil;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.StaffService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 员工管理 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class StaffServiceImpl implements StaffService {

    private final StaffMapper staffMapper;

    private final StaffTeamMapper staffTeamMapper;

    private final StaffTeamRelateMapper staffTeamRelateMapper;

    private final ActivityMapper activityMapper;

    private final StaffActivityRelateMapper staffActivityRelateMapper;

    private final GroupPurchaseGoodsItemMapper groupPurchaseGoodsItemMapper;

    private final MemberMapper memberMapper;

    private final WxUserMapper wxUserMapper;

    private final MemberGroupPurchaseItemMapper memberGroupPurchaseItemMapper;

    private final ShareMapper shareMapper;

    private final ShareRecordMapper shareRecordMapper;

    @Override
    public TableDataInfo<StaffListVO> pageList(StaffListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId())
            .eq("a.deleted",0)
            .like(StringUtils.isNotBlank(params.getRealname()),"a.realname",params.getRealname())
            .like(StringUtils.isNotBlank(params.getMobile()),"a.mobile",params.getMobile());
        Page<StaffListVO> result = staffMapper.selectPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean editStaff(StaffDO staffDO) {
        return staffMapper.updateById(staffDO) > 0;
    }

    @Override
    public Boolean deleteStaffByIds(Long[] staffIds) {
        List<Long> ids = Arrays.asList(staffIds);
        return staffMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public StaffVO getDetailById(Long staffId) {
        return staffMapper.selectVoById(staffId);
    }

    @Override
    public TableDataInfo<StaffTeamVO> teamPageList(TeamListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.eq("a.deleted",0);
        wrapper.eq("a.activity_id",params.getActivityId());
        wrapper.orderByDesc("a.create_time");
        Page<StaffTeamVO> result = staffMapper.selectTeamPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean addStaffTeam(StaffTeamDO staffTeamDO) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        staffTeamDO.setUserId(loginUser.getUserId());
        return staffTeamMapper.insert(staffTeamDO) > 0;
    }

    @Override
    public boolean checkTeamNameUnique(StaffTeamDO staffTeamDO) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        boolean exist = staffTeamMapper.exists(new LambdaQueryWrapper<StaffTeamDO>()
            .eq(StaffTeamDO::getTeamName, staffTeamDO.getTeamName())
            .eq(StaffTeamDO::getActivityId, staffTeamDO.getActivityId())
            .eq(StaffTeamDO::getUserId, loginUser.getUserId())
            .eq(StaffTeamDO::getDeleted,0)
            .ne(ObjectUtil.isNotNull(staffTeamDO.getId()), StaffTeamDO::getId, staffTeamDO.getId()));
        return !exist;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteStaffTeamByIds(Long[] teamIds) {
        List<Long> ids = Arrays.asList(teamIds);
        /**
         * 删除战队关联
         */
        QueryWrapper<StaffTeamRelateDO> wrapper = Wrappers.query();
        wrapper.in("team_id",ids);
        staffTeamRelateMapper.delete(wrapper);
        return staffTeamMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<StaffListVO> teamStaffPageList(TeamStaffListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("a.team_id",params.getId())
            .eq("b.user_id",loginUser.getUserId())
            .and(StringUtils.isNotBlank(params.getKeyword()),wrapper1 -> wrapper1.like("c.nickname",params.getKeyword()).or()
                .like("b.realname",params.getKeyword()))
            .eq("b.deleted",0);
        Page<StaffListVO> result = staffMapper.getTeamStaffPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean removeTeamStaff(Long staffId, Long teamId) {
        QueryWrapper<StaffTeamRelateDO> wrapper = Wrappers.query();
        wrapper.eq("staff_id",staffId).eq(" team_id",teamId);
        return staffTeamRelateMapper.delete(wrapper) > 0;
    }

    @Override
    public TableDataInfo<NoExistTeamStaffListVO> teamNoExistStaffPageList(TeamStaffListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        Page<NoExistTeamStaffListVO> result = staffMapper.teamNoExistStaffPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean addStaffToTeam(Long[] staffIds, Long teamId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        StaffTeamDO staffTeamDO = staffTeamMapper.selectById(teamId);
        if (staffTeamDO == null) {
            throw new ServiceException("战队不存在");
        }
        List<Long> staffIdList = Arrays.asList(staffIds);
        LambdaQueryWrapper<StaffDO> lqw = Wrappers.lambdaQuery();
        lqw.in(StaffDO::getId,staffIdList).eq(StaffDO::getDeleted,0);
        List<StaffDO> staffDOList = staffMapper.selectList(lqw);
        List<StaffTeamRelateDO> list = new ArrayList<>();
        staffDOList.forEach(item -> {
            StaffTeamRelateDO staffTeamRelateDO = new StaffTeamRelateDO();
            staffTeamRelateDO.setStaffId(item.getId());
            staffTeamRelateDO.setTeamId(teamId);
            list.add(staffTeamRelateDO);
        });
        if (list.size() > 0) {
            return staffTeamRelateMapper.insertBatch(list);
        }
        return true;
    }

    @Override
    public TableDataInfo<IsVisitActivityStaffListVO> getIsVisitStaffPageList(IsVisitStaffListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        Page<IsVisitActivityStaffListVO> result = staffMapper.getIsVisitStaffPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addStaffActivityVisitAuth(Long[] staffIds, Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (activityDO == null) {
            throw new ServiceException("活动不存在");
        }
        /**
         * 删除关联
         */
        QueryWrapper<StaffActivityRelateDO> wrapper = Wrappers.query();
        wrapper.eq("activity_id",activityId);
        staffActivityRelateMapper.delete(wrapper);
        List<Long> staffIdList = Arrays.asList(staffIds);

        /**
         * 获取员工数量
         */
        long staffCount = staffMapper.selectCount(new LambdaQueryWrapper<StaffDO>()
            .eq(StaffDO::getUserId, loginUser.getUserId())
            .eq(StaffDO::getDeleted, 0));

        /**
         * 根据员工id查询员工列表
         */
        LambdaQueryWrapper<StaffDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(StaffDO::getUserId,loginUser.getUserId())
            .eq(StaffDO::getDeleted,0)
            .in(StaffDO::getId,staffIdList);
        List<StaffDO> staffDOS = staffMapper.selectList(lqw);
        if (staffDOS.size() > 0) {
            if (staffDOS.size() == staffCount) {
                activityDO.setIsAllStaffVisible(1);
            } else {
                activityDO.setIsAllStaffVisible(0);
            }
            List<StaffActivityRelateDO> addList = new ArrayList<>();
            staffDOS.forEach(item -> {
                StaffActivityRelateDO staffActivityRelateDO = new StaffActivityRelateDO();
                staffActivityRelateDO.setActivityId(activityId);
                staffActivityRelateDO.setStaffId(item.getId());
                addList.add(staffActivityRelateDO);
            });
            if (addList.size() > 0) {
                staffActivityRelateMapper.insertBatch(addList);
            }
        }
        return activityMapper.updateById(activityDO) > 0;
    }

    @Override
    public List<StaffListVO> relateActivityStaffList(Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return staffMapper.relateActivityStaffList(loginUser.getUserId(),activityId);
    }

    @Override
    public List<StaffTeamVO> teamListByActivity(Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        LambdaQueryWrapper<StaffTeamDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(StaffTeamDO::getUserId,loginUser.getUserId())
            .eq(StaffTeamDO::getActivityId,activityId)
            .eq(StaffTeamDO::getDeleted,0).orderByAsc(StaffTeamDO::getCreateTime);
        return staffTeamMapper.selectVoList(lqw);
    }

    @Override
    public TableDataInfo<StaffDetailListVO> staffDetailPageList(StaffTeamDataParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.eq("a.activity_id",params.getActivityId());
        if (params.getEnrollDateRange() != null && params.getEnrollDateRange().size() > 0) {
            wrapper.between("a.create_time",params.getEnrollDateRange().get(0),params.getEnrollDateRange().get(1));
        }
        wrapper.eq(ObjectUtil.isNotNull(params.getTeamId()),"st.id",params.getTeamId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getRealname()),"s.realname",params.getRealname());
        wrapper.eq(ObjectUtil.isNotNull(params.getIdentity()),"tmgpi.identity",params.getIdentity());
        wrapper.orderByDesc("a.create_time");
        Page<StaffDetailListVO> result = staffMapper.staffDetailPageList(pageQuery.build(),wrapper);
        if (result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {
                if (item.getIdentity() != null && item.getIdentity() == 1) {
                    List<MemberGroupPurchaseItemListVO> list = memberGroupPurchaseItemMapper.getItemList(item.getGroupPurchaseId());
                    item.setList(list);
                }
            });
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<StaffRankListVO> staffRankPageList(StaffTeamDataParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getStatsDateRange() != null && params.getStatsDateRange().size() > 0) {
            params.setStartStatsDateRange(params.getStatsDateRange().get(0));
            params.setEndStatsDateRange(params.getStatsDateRange().get(1));
        }
        Page<StaffRankListVO> result = staffMapper.staffRankPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<StaffRankListVO> teamStatsPageList(StaffTeamDataParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getStatsDateRange() != null && params.getStatsDateRange().size() > 0) {
            params.setStartStatsDateRange(params.getStatsDateRange().get(0));
            params.setEndStatsDateRange(params.getStatsDateRange().get(1));
        }
        Page<StaffRankListVO> result = staffMapper.teamStatsPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    public StaffVO getDetailByWxId(Long wxUserId,Long userId) {
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("user_id",userId);
        wrapper.eq("wx_user_id",wxUserId);
        wrapper.eq("deleted",0);
        return staffMapper.selectVoOne(wrapper);
    }

    public MemberDetailVO getDetailByOpenId(String openId,Long userId) {
        return memberMapper.selectDetailByOpenId(openId,userId);
    }
    public R<T> register(WxStaffRegisterParams params) {
        //根据openid查询member
        MemberDetailVO memberDetailVO = getDetailByOpenId(params.getOpenId(),params.getUserId());
        if(ObjectUtil.isEmpty(memberDetailVO)){
            //注册客户信息
            WxUserVO wxUserVO = getWxUserByOpenId(params.getOpenId());
            if(ObjectUtil.isEmpty(wxUserVO)){
                WxUserDO wxUserDO = saveWxUser(params.getOpenId());
                wxUserVO = new WxUserVO();
                wxUserVO.setId(wxUserDO.getId());
            }
            MemberDO memberDO = new MemberDO();
            memberDO.setWxUserId(wxUserVO.getId());
            memberDO.setUserId(params.getUserId());
            memberDO.setCreateTime(DateUtil.getDateTime());
            memberDO.setName(params.getRealname());
            memberDO.setMobile(params.getMobile());
            memberMapper.insert(memberDO);
            memberDetailVO = new MemberDetailVO();
            memberDetailVO.setWxUserId(memberDO.getWxUserId());
            memberDetailVO.setId(memberDO.getId());
        }
        StaffVO staffVO = getDetailByWxId(memberDetailVO.getWxUserId(),params.getUserId());
        if(ObjectUtil.isEmpty(staffVO)){
            StaffDO staffDO = new StaffDO();
            staffDO.setMemberId(memberDetailVO.getId());
            staffDO.setWxUserId(memberDetailVO.getWxUserId());
            staffDO.setRealname(params.getRealname());
            staffDO.setMobile(params.getMobile());
            staffDO.setIsVerification(params.getIsVerification());
            staffDO.setDeleted(0);
            staffDO.setUserId(params.getUserId());
            staffMapper.insert(staffDO);

            /**
             * 查看活动自动设置员工可见
             */
            LambdaQueryWrapper<ActivityDO> lqw = new LambdaQueryWrapper<ActivityDO>();
            lqw.eq(ActivityDO::getIsAllStaffVisible,1)
                .eq(ActivityDO::getIsDraft,0)
                .eq(ActivityDO::getDeleted,0);
            List<ActivityDO> activityDOS = activityMapper.selectList(lqw);
            if (activityDOS != null && activityDOS.size() > 0) {
                List<StaffActivityRelateDO> addList = new ArrayList<>();
                activityDOS.forEach(item -> {
                    StaffActivityRelateDO staffActivityRelateDO = new StaffActivityRelateDO();
                    staffActivityRelateDO.setActivityId(item.getId());
                    staffActivityRelateDO.setStaffId(staffDO.getId());
                    addList.add(staffActivityRelateDO);
                });
                if (addList.size() > 0) {
                    staffActivityRelateMapper.insertBatch(addList);
                }
            }
            return R.ok("提交申请成功");
        }else{
            return R.fail("员工已注册");
        }


    }

    public void updateBaseInfo(WxStaffUpdateParams params,Long id) {
        StaffDO staffDO = staffMapper.selectById(id);
        if(ObjectUtil.isNotEmpty(staffDO)){
            staffDO.setMobile(params.getMobile());
            staffDO.setRealname(params.getRealname());
            staffMapper.updateById(staffDO);
        }else{
            throw new ServiceException("员工不存在");
        }
    }
    public void updateQrCode(String qr,Long id) {
        StaffDO staffDO = staffMapper.selectById(id);
        if(ObjectUtil.isNotEmpty(staffDO)) {
            staffDO.setWxQrCode(qr);
            staffMapper.updateById(staffDO);
        }else{
            throw new ServiceException("员工不存在");
        }
    }

    public WxUserVO getWxUserByOpenId(String openId) {
        QueryWrapper<WxUserDO> wrapper = Wrappers.query();
        wrapper.eq("open_id",openId);
        return wxUserMapper.selectVoOne(wrapper);
    }
    public WxUserDO saveWxUser(String openId) {
        WxUserDO wxUserDO = new WxUserDO();
        wxUserDO.setOpenId(openId);
        wxUserDO.setCreateTime(DateUtil.getDateTimeString());
        wxUserMapper.insert(wxUserDO);
        return wxUserDO;
    }

    /**
     * 员工商家列表
     * @param openId
     * @return
     */
    public List<WxStaffSysUseVO> getStaffSysUserList(String openId) {
        return staffMapper.selectStaffSysUser(openId);
    }

    @Override
    public Map<String, Object> getShareIdAndShareRecordId(WxStaffDetailVO wxStaffDetailVO, Long activityId, Long memberId) {
        Map<String, Object> map = new HashMap();
        MemberDO memberDO = memberMapper.selectById(memberId);
        if (memberDO == null) {
            throw new ServiceException("客户信息不存在");
        }
        LambdaQueryWrapper<ShareDO> shareWrapper = Wrappers.lambdaQuery(ShareDO.class);
        shareWrapper.eq(ShareDO::getProductId,activityId).eq(ShareDO::getMemberId,memberId);
        shareWrapper.last("limit 1");
        ShareDO shareDO = shareMapper.selectOne(shareWrapper);
        if (shareDO == null) {
            ShareDO shareAdd = new ShareDO();
            shareAdd.setMemberId(memberId);
            shareAdd.setMemberWxUserId(memberDO.getWxUserId());
            shareAdd.setProductId(activityId);
            shareAdd.setProductType(1);
            shareAdd.setShareNumber(0);
            shareAdd.setSpreadNumber(0);
            shareAdd.setMemberBuyNumber(0);
            shareAdd.setBuyNumber(0);
            shareAdd.setPayTotal(BigDecimal.ZERO);
            shareAdd.setEnrollStatus(2);//未报名
            shareAdd.setUserId(memberDO.getUserId());
            shareMapper.insert(shareAdd);
            map.put("shareId",shareAdd.getId());
        } else {
            map.put("shareId",shareDO.getId());
        }
        ShareRecordDO shareRecordDO = new ShareRecordDO();
        shareRecordDO.setShareStaffId(wxStaffDetailVO.getId());
        shareRecordDO.setStaffWxUserId(wxStaffDetailVO.getWxUserId());
        shareRecordDO.setShareId(Convert.toLong(map.get("shareId")));
        shareRecordDO.setPassiveMemberId(memberId);
        shareRecordDO.setPassiveMemberWxUserId(memberDO.getWxUserId());
        shareRecordDO.setPreviousShareRecordId(0L);
        shareRecordDO.setUserId(memberDO.getUserId());
        shareRecordMapper.insert(shareRecordDO);
        map.put("shareRecordId",shareRecordDO.getId());
        return map;
    }

    @Override
    public StaffVO getStaffInfo(String id) {
        return staffMapper.selectVoById(id);
    }

    @Override
    public void removeStaff(Long uid, Long wxUserId) {
        StaffDO staffDO = staffMapper.selectOne(new LambdaQueryWrapper<StaffDO>()
            .eq(StaffDO::getWxUserId, wxUserId).eq(StaffDO::getUserId, uid)
            .eq(StaffDO::getDeleted, 0));
        if (staffDO == null) {
            throw new ServiceException("您不是该商家的员工");
        }
        staffMapper.deleteById(staffDO);
    }
}
